import React, { useState, Fragment } from 'react';
import {
    Table, Tag, Button,
    message, Modal, Upload
} from 'antd';
import { Image } from 'antd';
import {
    UploadOutlined ,
} from '@ant-design/icons';
import Head from 'next/head';
import Router, { withRouter } from 'next/router'
import { Editor as BraftEditor } from '@/components/Editor'
import { copyCode } from '@/utils'
import { apiUrl } from '@/api/baseUrl'
import AdvancedSearchForm from '@/components/Form'

const columns = (props) => {
    const { userinfo } = props.state
    return [
        {
            title: '文件名',
            dataIndex: 'name',
            key: 'name',
            width: 100,
            align: 'center',
            rowKey: record => record.dataIndex,
            render: name => <p className={'text-left ellipsis2'}>{name}</p>,
        },
        {
            title: '图片文件预览',
            dataIndex: 'url',
            key: 'url',
            width: 80,
            align: 'center',
            rowKey: record => record.dataIndex,
            render: url => <div>
                <Image src={url} style={{ height: 60, width: 'auto' }} fit={'cover'} placeholder={<p style={{height: 60, lineHeight: '60px', textAlign: 'center', backgroundColor: 'rgba(255,255,255,0.9)'}}>加载中...</p>} />
            </div>,
        },
        {
            title: '文件路径',
            dataIndex: 'url',
            key: 'url',
            width: 200,
            height: 80,
            ellipsis: 2,
            align: 'center',
            rowKey: record => record.dataIndex,
            render: url =>
                <div className={'ellipsis'}>
                    <span>{url}</span>
                </div>,
        },
        {
            title: '上传时间',
            dataIndex: 'createTime',
            key: 'createTime',
            width: 100,
            height: 80,
            ellipsis: 2,
            align: 'center',
            rowKey: record => record.dataIndex,
            render: createTime =>
                <div>
                    <span>{React.$filters.timeFilter(new Date(createTime).getTime())}</span>
                </div>,
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            align: 'center',
            render: (text, record) => (
                <span>
                    <a style={{ marginRight: 16 }} onClick={() => props.handleCopy(text)}>复制路径</a>
                    {userinfo && userinfo.administrator && <a style={{ marginRight: 16 }} onClick={() => props.handleDelete(record)}>删除</a>}
                </span>
            ),
        },
    ];
}
class FilePage extends React.Component {
    constructor(props) {
        super(props)
    }
    static async getInitialProps ({ $api, userinfo }) {
        // 从query参数中回去id
        //通过process的browser属性判断处于何种环境：Node环境下为false,浏览器为true
        // 发送服务器请求
        const res = await $api.file.get({ current: 1, pageSize: 10 })
        if (res && res.success) {
            return {
                loading: false,
                data: res.data.records,
                pageData: {
                    current: 1,
                    pageSize: 10,
                    total: res.data.total,
                    pageSizeOptions: [5, 10, 20, 50]
                },
                userinfo,
            }
        } else {
            return {
                loading: true,
                data: [],
                pageData: {
                    current: 1,
                    pageSize: 10,
                    total: 999,
                    pageSizeOptions: [5, 10, 20, 50]
                },
                userinfo,
            }
        }
    }

    state = {
        loading: true,
        data: this.props.data,
        pageData: this.props.pageData,
        queryData: {},
        hasData: true,
        modalVisible: false,
        reviewData: {},
        userinfo: this.props.userinfo,
        formItems: [
            {
                label: '文件名称',
                type: 1,
                name: 'name',
                placeholder: '文件名称'
            }
        ],
        scroll: {
            y: 400
        },
        props: {
            name: 'file',
            action: apiUrl + '/upload',
            headers: {
              authorization: '',
            },
            multiple: true,
            showUploadList: false,
            onChange: (info) => {
              if (info.file.status !== 'uploading') {
                // console.log(info.file, info.fileList);
              }
              if (info.file.status === 'done') {
                message.success(`上传成功`);
                this.getPageData({}, true)
              } else if (info.file.status === 'error') {
                message.error(`上传失败`);
              }
            },
        }
    }
    async handlerFormSubmit (values, isPage) {
        isPage && this.setState({ loading: true, pageData: values })
        !isPage && this.setState({
            loading: true,
            queryData: values,
            pageData: {
                current: 1,
                pageSize: 10,
                total: this.state.pageData.total,
                pageSizeOptions: [5, 10, 20, 50]
            }
        })
        // 发送服务器请求
        const { current, pageSize } = isPage ? values : this.state.pageData
        const queryData = {}
        for (const key in this.state.queryData) {
            if (this.state.queryData[key]) {
                queryData[key] = this.state.queryData[key]
            }
        }
        const params = { current, pageSize, ...queryData }
        this.getPageData(params)
    }
    async getPageData (params = {}, isPage) {
        isPage && this.setState({ loading: true })
        const { current:currentPage, pageSize, name } = { ...this.state.pageData, ...params }
        const res = await $api.file.get({ currentPage, pageSize, name })
        if (res && res.success) {
            this.setState({
                loading: false,
                data: res.data.records,
                pageData: {
                    current: currentPage,
                    pageSize,
                    total: res.data.total
                }
            })
        } else {
            this.setState({
                loading: false,
                data: [],
                pageData: {
                    current,
                    pageSize,
                    total: 0,
                }
            })
        }
    }
    // 复制文件路径
    handleCopy = (item) => {
        copyCode(item.url)
        message.success('复制成功！')
    }
    // 删除文件
    handleDelete (item) {
        $api.file.delete({ ids: [item.id] }).then(res => {
            if (res && res.success) {
                message.success(res.data)
                this.getPageData(this.props.pageData)
            } else {
                res && message.error(res.message)
            }
        })
    }
    setArticle (callback) {
        return callback(this.state.reviewData)
    }
    componentDidMount () {
        this.setState({ loading: false, scroll : { y: window.innerHeight - 400 } })
        // 如果没有缓存，通过localStorage在本地缓存数据
        // sessionStorage.setItem('articleList', JSON.stringify(this.props.data))
        window.addEventListener('resize', () => {
            this.setState({ ...this.state, scroll : { y: window.innerHeight - (this.state.showMore ? 450 : 400) } })
        })
    }
    setModalVisible (modalVisible) {
        this.setState({ modalVisible });
    }
    render () {
        const { ...state } = this.state
        return (
            <Fragment>
                <Head>
                    <title>文件列表</title>
                </Head>
                {/* <h3 className='text-gray-600 text-lg leading-4 mb-5 divide-x border-solid border-l-4 pl-2 border-orange-f9'>文件列表</h3> */}
                <AdvancedSearchForm
                title={'评论列表'}
                formItems={state.formItems}
                setParentState={this.handlerFormSubmit.bind(this)}
                actions={
                    <Upload className='float-right' {...state.props}>
                        <Button icon={<UploadOutlined  />}>上传文件</Button>
                    </Upload>
                }
                />
                <Table
                    {...this.state}
                    className="file-table"
                    scroll={state.scroll}
                    rowKey={(record, index) => index}
                    dataSource={state.hasData ? this.state.data : null}
                    columns={columns(this)}
                    handleDelete={(val) => this.handleDelete(val)}
                    handleReview={(val) => this.handleReview(val)}
                    onChange={(pageData) => this.handlerFormSubmit(pageData, true)}
                    pagination={{
                        ...this.state.pageData,
                        showSizeChanger: true,
                        showTitle: (total, range) => '页',
                        showTotal: (total, range) => `共 ${total} 条`
                    }}
                />
                <Modal
                    title="文件详情"
                    centered
                    width={800}
                    footer={null}
                    visible={this.state.modalVisible}
                    onOk={() => this.setModalVisible(false)}
                    onCancel={() => this.setModalVisible(false)}
                >
                    <div className="review-content">
                        <h3 className="text-xl mb-5">{this.state.reviewData.title}</h3>
                        {/* <div dangerouslySetInnerHTML={{ __html: this.state.reviewData.content }}></div> */}
                        <BraftEditor
                            value={this.state.reviewData.content}
                            onChange={(value) => {
                                this.setArticle((article) => {
                                    article.content = value;
                                    return article;
                                });
                            }}
                        ></BraftEditor>
                        <p className="tags">
                            <h3 className="text-2 mb-5 mt-5">关联标签</h3>
                            <span>
                                {this.state.reviewData.tags && this.state.reviewData.tags.map((tag, index) => {
                                    let color = index > 1 ? 'geekblue' : 'green';
                                    if (tag.value === '前端') {
                                        color = 'volcano';
                                    }
                                    return (
                                        <Tag color={color} key={tag.id} className="mb-1">
                                            {tag.value.toUpperCase()}
                                        </Tag>
                                    );
                                })}
                            </span>
                        </p>
                    </div>
                </Modal>
            </Fragment>
        )
    }
}
export default FilePage